<template>
  <view class="mobile-item-container">
    <view
      v-for="(item, subIndex) in list"
      :key="subIndex"
      @click="playAudio(item)"
      class="music-item"
    >
      <view class="item-cover" style="width: 300rpx; margin: 0px 10px;">
        <image :src="item.cover" mode="aspectFill" class="cover-img"></image>
        <view class="play-icon">
          <up-icon name="play-circle" size="28" color="#4d4d4d"></up-icon>
        </view>
      </view>
      <view class="item-info">
        <text class="item-name">{{ item.name }}</text>
        <!-- 修复可能的变量声明问题，确保formatDuration函数在使用前已正确声明 -->
        <text class="item-duration">{{ formatDuration(item.duration) }}</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import { getMusicList } from '@/api/music';
import { ref } from 'vue';
import type { MusicItem } from '@/types/music';

const list = ref<MusicItem[]>([]);
const title = ref<string>('');

const getMusicData = async (title: string) => {
  try {
    const response = await getMusicList(title);
    // @ts-ignore
    const musicListData = response.data;
    list.value = musicListData.map((music: any) => {
      return {
        id: music.musicId,
        name: music.name,
        singer: music.singer,
        album: music.album,
        url: `${process.env.BASE_URL}${music.url}`,
        cover: `${process.env.BASE_URL}${music.cover}`,
        duration: music.duration,
        isCollected : music.isCollected
      } as MusicItem; // 明确类型
    });
  } catch (error) {
    console.error('音乐数据获取失败:', error);
  }
};

const playAudio = (item: MusicItem) => {
  uni.navigateTo({
    url: `/pages/music/musicPlaying?id=${item.id}&title=${title.value}` // 传递id和title
  });
  console.log(`播放音频：${item.name}`);
};

const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
};

onLoad((options: any) => {
  title.value = options.title;
  uni.setNavigationBarTitle({
    title: options.title
  });
  getMusicData(options.title);
});

</script>

<style lang="scss" scoped>
/* 页面样式 */
.mobile-item-container {
  width: 100%;
  min-height: 80vh;
  background-color: #f0f2f4;
  display: flex; // 使用 Flexbox 布局
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: start;
  padding: 20px 0;
  gap: 20px; // 设置元素之间的间距
}

.music-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cover-img {
  width: 100%;
  height: 400rpx;
  border-radius: 20rpx;
}

.item-cover {
  position: relative;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.item-info {
  padding: 15rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.item-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.item-duration {
  color: #b2b2ac;
  font-size: 24rpx;
}
</style>